//
//  SDPhotoFullScreenViewController.m
//  SKinDiary
//
//  Created by pcyang on 16/7/17.
//  Copyright © 2016年 tencent. All rights reserved.
//

#import "SDPhotoFullScreenViewController.h"

@import Photos;

#define MINIMUM_SCALE 0.5f
#define MAXIMUM_SCALE 0.3f

@interface SDPhotoFullScreenViewController()<UIScrollViewDelegate, UIActionSheetDelegate>{
    CGFloat offset;
}
@property (nonatomic,strong)SDSimpleImageView* photoView;
@property (nonatomic,strong)UIScrollView* myScrollView;

@end

@implementation SDPhotoFullScreenViewController
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self initViews];
}

- (void)initViews
{
    BOOL naviHidden = [self navigationBarHidden];
    if (!naviHidden && self.navBar != nil)
    {
        [self.navBar setTitle:@"全图"];
        UIImage* addImg = LOAD_IMAGE_USE_CACHE_INBUNDLE(DefaultBundle, @"actionbar_btn_back.png");
        [self.navBar customNaviLeftButton:self action:@selector(onBack:) image:addImg];
    }

    
    self.myScrollView = [[UIScrollView alloc]initWithFrame:autoRectTableViewHaveBar(!naviHidden)];
    self.myScrollView.indicatorStyle = UIScrollViewIndicatorStyleWhite;
    self.myScrollView.delegate = self;
    self.myScrollView.backgroundColor = [UIColor clearColor];
    self.myScrollView.scrollEnabled = YES;
    self.myScrollView.pagingEnabled = YES;
    [self.view addSubview:self.myScrollView];
    
    UITapGestureRecognizer *doubleTap =[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleDoubleTap:)];
    [doubleTap setNumberOfTapsRequired:2];
    
    UILongPressGestureRecognizer *longTap =[[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongTap:)];
    
    UIScrollView *s = [[UIScrollView alloc] initWithFrame:self.myScrollView.bounds];
    s.backgroundColor = [UIColor clearColor];
    s.contentSize = CGSizeMake(CGRectGetWidth(_myScrollView.frame), CGRectGetHeight(_myScrollView.frame));
    s.delegate = self;
    s.minimumZoomScale = 1.0;
    s.maximumZoomScale = 4.0;
    [s setZoomScale:1.0];
    
    _photoView = [[SDSimpleImageView alloc] initWithFrame:_myScrollView.bounds];
    [_photoView setContentMode:UIViewContentModeScaleAspectFill];
    [_photoView addGestureRecognizer:doubleTap];
    [_photoView addGestureRecognizer:longTap];
    [self.myScrollView addSubview:_photoView];
    self.myScrollView.contentSize = _photoView.bounds.size;
    
    if (CHECK_VALID_STRING(_photoInfo.originalFileName)) {
        NSString* directory = [SDFile getDirectoryInCacheWithName:kPhotoDiretoryName];
        NSString *filePath = [directory stringByAppendingPathComponent:_photoInfo.originalFileName];
        if ([SDFile fileExist:filePath]) {
            UIImage* image = [UIImage imageWithContentsOfFile:filePath];
            _photoView.image = image;
        }
    } else {
        if (CHECK_VALID_STRING(_photoInfo.photoUrl)) {
            [_photoView setImageWithURL:_photoInfo.photoUrl];
        }
    }
    [s addSubview:_photoView];
    [self.myScrollView addSubview:s];
    self.automaticallyAdjustsScrollViewInsets = NO;

    self.myScrollView.translatesAutoresizingMaskIntoConstraints = NO;

}

- (BOOL)navigationBarHidden
{
    return NO;
}

- (void)onBack:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark - tap
-(void)handleDoubleTap:(UIGestureRecognizer *)gesture {
    float newScale;
    if ([(UIScrollView*)gesture.view.superview zoomScale] == 1) {
        newScale = [(UIScrollView*)gesture.view.superview zoomScale] * 2.0;
    } else {
        newScale = 1;
    }
    CGRect zoomRect = [self zoomRectForScale:newScale  inView:(UIScrollView*)gesture.view.superview withCenter:[gesture locationInView:gesture.view]];
    [(UIScrollView*)gesture.view.superview zoomToRect:zoomRect animated:YES];
}

- (void)handleLongTap:(UILongPressGestureRecognizer *)gesture {
    if ([gesture state] == UIGestureRecognizerStateBegan) {
        UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"图片保存" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"保存" otherButtonTitles:nil, nil];
        [actionSheet showInView:self.view];
    }
}

#pragma mark - Utility methods

- (CGRect)zoomRectForScale:(float)scale inView:(UIScrollView*)scrollView withCenter:(CGPoint)center {
    
    CGRect zoomRect;
    
    zoomRect.size.height = [scrollView frame].size.height / scale;
    zoomRect.size.width  = [scrollView frame].size.width  / scale;
    
    zoomRect.origin.x    = center.x - (zoomRect.size.width  / 2.0);
    zoomRect.origin.y    = center.y - (zoomRect.size.height / 2.0);
    
    return zoomRect;
}

#pragma mark - ScrollView delegate
-(UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView{
    
    for (UIView *v in scrollView.subviews){
        return v;
    }
    return nil;
}

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    
    if (scrollView == self.myScrollView){
        CGFloat x = scrollView.contentOffset.x;
        if (x==offset){
            
        }
        else {
            offset = x;
            for (UIScrollView *s in scrollView.subviews){
                if ([s isKindOfClass:[UIScrollView class]]){
                    [s setZoomScale:1.0];
                }
            }
        }
    }
}

#pragma mark - UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0) {
        [self saveImageToCustomAblum:_photoView.image];
    }
}

#pragma mark - save image
- (void)loadImageFinished:(UIImage *)image
{
    [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
        
        //写入图片到相册
        [PHAssetChangeRequest creationRequestForAssetFromImage:image];
        
    } completionHandler:^(BOOL success, NSError * _Nullable error) {
        
        NSLog(@"success = %d, error = %@", success, error);
        
    }];
}

/**拥有与 APP 同名的自定义相册--如果没有则创建*/
-(PHAssetCollection *)getAssetCollectionWithAppNameAndCreateIfNo
{
    //1 获取以 APP 的名称
    NSString *title = [NSBundle mainBundle].infoDictionary[(__bridge NSString *)kCFBundleNameKey];
    //2 获取与 APP 同名的自定义相册
    PHFetchResult<PHAssetCollection *> *collections = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
    for (PHAssetCollection *collection in collections) {
        //遍历
        if ([collection.localizedTitle isEqualToString:title]) {
            //找到了同名的自定义相册--返回
            return collection;
        }
    }
    
    //说明没有找到，需要创建
    NSError *error = nil;
    __block NSString *createID = nil; //用来获取创建好的相册
    [[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
        //发起了创建新相册的请求，并拿到ID，当前并没有创建成功，待创建成功后，通过 ID 来获取创建好的自定义相册
        PHAssetCollectionChangeRequest *request = [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:title];
        createID = request.placeholderForCreatedAssetCollection.localIdentifier;
    } error:&error];
    if (error) {
        return nil;
    }else{
        //通过 ID 获取创建完成的相册 -- 是一个数组
        return [PHAssetCollection fetchAssetCollectionsWithLocalIdentifiers:@[createID] options:nil].firstObject;
    }
    
}

/**将图片保存到自定义相册中*/
-(void)saveImageToCustomAblum:(UIImage *)image
{
    //拥有自定义相册（与 APP 同名，如果没有则创建）--调用刚才的方法
    PHAssetCollection *assetCollection = [self getAssetCollectionWithAppNameAndCreateIfNo];
    if (assetCollection == nil) {
        return;
    }
    
    //将刚才保存到相机胶卷的图片添加到自定义相册中 --- 保存带自定义相册--属于增的操作，需要在PHPhotoLibrary的block中进行
    NSError *error = nil;
    [[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
        //--告诉系统，要操作哪个相册
        PHAssetCollectionChangeRequest *collectionChangeRequest = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:assetCollection];
        
        PHAssetChangeRequest *assetChangeRequest = [PHAssetChangeRequest creationRequestForAssetFromImage:image];

        PHObjectPlaceholder *placeholder = [assetChangeRequest placeholderForCreatedAsset];
        
        [collectionChangeRequest addAssets:@[placeholder]];
    } error:&error];
    
    
    if (error) {
        return;
    }
}
@end
